(function() {
	var $optimizeForm = $('#optimize-form');
	var $otherWords = $('div.other-words', $optimizeForm);
	var $customWordInput = $('input[name="customWord"]', $otherWords);
	var $newTitle = $('input.new-title', $optimizeForm);
	
	$('a.word', $otherWords).live('click', function(){
		var title = $newTitle.val();
		title += $(this).text();
		$newTitle.val(title);
		$newTitle.focus();
		return false;
	});
	
	$('div.word a.delete-tool', $otherWords).live('click', function(){
		var $word = $(this).parent();
		var word = $word.find('a.word').text();
		$.ajax({
			url: 'delete-custom-word',
			data: {
				word: word
			},
			type: 'POST',
			success: function(data, textStatus, jqXHR){
				var error = jqXHR.getResponseHeader('error');
				if (error)
				{
					alert("添加失败，请重试。");
					return false;
				}
				$word.remove();
			}
		});
		return false;
	});
	
	function addCustomWord($input)
	{
		var word = $input.val();
		$.ajax({
			url: 'add-custom-word',
			data: {
				word: word
			},
			type: 'POST',
			success: function(data, textStatus, jqXHR){
				var error = jqXHR.getResponseHeader('error');
				if (error)
				{
					alert("添加失败，请重试。");
					return false;
				}
				var $word = $('<div class="word">'
						+ '<a href="#" title="点击添加到新标题" class="word"></a>'
						+ '<a href="#" class="delete-tool ui-icon ui-icon-circle-close" title="删除"></a>'
						+ '<span>,&nbsp;</span>'
						+ '<div class="clear"></div>'
						+ '</div>');
				$word.find('a.word').text(word);
				$word.insertBefore($('div.custom-words div.panel-content>div.clear', $otherWords));
				$input.val('');
				$input.focus();
			}
		});
	}
	
	$('button.add', $otherWords).click(function(){
		addCustomWord($customWordInput);
		return false;
	});
	
	$customWordInput.keypress(function(event){
		if (event.which === 13)
		{
			addCustomWord($(this));
			return false;
		}
	});
})();